from . import db
from datetime import datetime

class Vehicle(db.Model):
    __tablename__ = 'vehicles'
    
    id = db.Column(db.Integer, primary_key=True)
    license_plate = db.Column(db.String(20), unique=True, nullable=False)
    brand = db.Column(db.String(50))
    model = db.Column(db.String(50))
    year = db.Column(db.Integer)
    vehicle_type = db.Column(db.String(50))  # 车辆类型：货车、客车、工程车等
    capacity = db.Column(db.String(50))  # 载重或载客量
    fuel_type = db.Column(db.String(20))  # 燃料类型
    status = db.Column(db.String(20), default='available')  # available, in_use, maintenance, retired
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), nullable=True)
    group = db.relationship('Group', backref='vehicles')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'license_plate': self.license_plate,
            'brand': self.brand,
            'model': self.model,
            'year': self.year,
            'vehicle_type': self.vehicle_type,
            'capacity': self.capacity,
            'fuel_type': self.fuel_type,
            'status': self.status,
            'is_active': self.is_active,
            'group_id': self.group_id,
            'group_name': self.group.name if self.group else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Vehicle {self.license_plate}>'
